from flask import render_template, request, session, jsonify, g, redirect, url_for, json

from models import db
from models.index import Review, Cart, Product, Order
from utils.common import get_p_count
from . import user_blu


@user_blu.route("/review.html", methods=["POST"])
def review():
    content = request.json.get("content")
    p_id = request.json.get("p_id")
    user_id = session.get("user_id")
    if not user_id:
        return jsonify({
            "errno": 2001,
            "errmsg": "请先登录"
        })
    comment = Review(user_id=user_id, product_id=p_id, content=content)
    try:
        db.session.add(comment)
        db.session.commit()
        comment = db.session.query(Review).filter(Review.user_id == user_id, Review.product_id == p_id).order_by(
            -Review.create_time).first()
        user = comment.user.__dict__
        comment_dict = comment.__dict__
        del user['_sa_instance_state']
        del comment_dict['_sa_instance_state']
        comment_dict["user"] = user
        ret = {
            "errno": 0,
            "errmsg": "评论成功"
        }
        ret["comment"] = comment_dict
    except:
        ret = {
            "errno": 2002,
            "errmsg": "评论失败"
        }
    return ret


@user_blu.route("/cart.html")
def cart():
    if not g.user:
        return render_template("cart.html")
    p_in_cart = g.user.my_cart
    count_my_cart = len(p_in_cart)
    cart_total = 0
    for p in p_in_cart:
        cart_total += p.price * get_p_count(p)
    return render_template("cart.html", user=g.user, p_in_cart=p_in_cart, count_my_cart=count_my_cart,
                           cart_total=cart_total)


@user_blu.route("/add_to_cart.html", methods=["POST"])
def add_to_cart():
    if not g.user:
        return redirect(url_for("passport.signin"))
    p_id = request.json.get("p_id")
    quantity = request.json.get("quantity", 1)
    p = db.session.query(Cart).filter(Cart.user_id == g.user.id, Cart.product_id == p_id).first()
    product = db.session.query(Product).filter(Product.id == p_id).first()
    product = product.__dict__
    if not p:
        try:
            add_cart = Cart()
            add_cart.user_id = g.user.id
            add_cart.product_id = p_id
            add_cart.quantity = quantity
            db.session.add(add_cart)
            db.session.commit()
            del product['_sa_instance_state']
            product["cart"] = add_cart.quantity
            print(product)
            ret = {
                "errno": 0,
                "errmsg": "添加成功"
            }
            ret["product"] = product
        except Exception as e:
            ret = {
                "errno": 2001,
                "errmsg": "未查询到该商品"
            }
    else:
        try:
            p.quantity += int(quantity)
            db.session.commit()
            del product['_sa_instance_state']
            product["cart"] = p.quantity
            ret = {
                "errno": 1,
                "errmsg": "添加成功"
            }
            ret["product"] = product
        except Exception as e:
            print(e)
            ret = {
                "errno": 2002,
                "errmsg": "添加失败"
            }
    return jsonify(ret)


@user_blu.route("/del_product.html", methods=["POST"])
def del_product():
    p_id = request.json.get("p_id")
    user_id = g.user.id
    del_cart = db.session.query(Cart).filter(Cart.product_id == p_id, Cart.user_id == user_id).first()
    try:
        db.session.delete(del_cart)
        db.session.commit()
        del_price = del_cart.quantity * db.session.query(Product).filter(Product.id == p_id).first().price
        ret = {
            "errno": 0,
            "errmsg": "删除成功"
        }
        ret["p_id"] = p_id
        ret["del_price"] = del_price
    except:
        ret = {
            "errno": 4001,
            "errmsg": "删除失败"
        }
    return jsonify(ret)


@user_blu.route("/get_data.html", methods=["POST"])
def get_data():
    products = request.json.get("products")
    session["products"] = products
    session["is_single"] = None
    return jsonify({
        "errno": 0,
        "errmsg": "成功"
    })


@user_blu.route("/get_single_data.html", methods=["POST"])
def get_single_data():
    pid = request.json.get("p_id")
    quantity = request.json.get("quantity")
    is_single = request.json.get("is_single")
    product = dict()
    product[pid] = quantity
    session["product"] = product
    session["is_single"] = is_single
    return jsonify({
        "errno": 0,
        "errmsg": "获取成功"
    })


@user_blu.route("/checkout.html")
def checkout():
    if not g.user:
        return render_template('checkout.html')
    products = session.get("products")
    single_pro = session.get("product")
    is_single = session.get("is_single")
    print(is_single)
    if not is_single:
        total_price = 0
        for k, v in products.items():
            product_in_cart = db.session.query(Cart).filter(Cart.user_id == g.user.id, Cart.product_id == k).first()
            product_in_cart.quantity = int(v)
            product = db.session.query(Product).filter(Product.id == k).first()
            total_price += product.price * int(v)
        db.session.commit()
        p_in_cart = g.user.my_cart
        total_count = len(p_in_cart)
        return render_template('checkout.html', user=g.user, total_price=total_price, p_in_cart=p_in_cart,
                               total_count=total_count)

    total_price = 0
    for k, v in single_pro.items():
        total_price += db.session.query(Product).filter(Product.id == k).first().price * int(v)
    p_in_cart = g.user.my_cart
    total_count = len(p_in_cart)
    return render_template('checkout.html', user=g.user, total_price=total_price, p_in_cart=p_in_cart,
                           total_count=total_count)


@user_blu.route("/pay.html")
def pay():
    products = session.get("products")
    product = session.get("product")
    is_single = session.get("is_single")
    order = Order()
    order.user_id = g.user.id
    print(is_single)
    if not is_single:
        total_price = 0
        for k, v in products.items():
            product_in_cart = db.session.query(Cart).filter(Cart.user_id == g.user.id, Cart.product_id == k).first()
            product_in_cart.quantity = product_in_cart.quantity - int(v)
            p = db.session.query(Product).filter(Product.id == k).first()
            p.amount -= int(v)
            p.sales += int(v)
            total_price += p.price * int(v)
            if product_in_cart.quantity == 0:
                db.session.delete(product_in_cart)
        order.products = json.dumps(products)
        order.total_price = total_price
        db.session.commit()
    else:
        total_price = 0
        for k, v in product.items():
            p = db.session.query(Product).filter(Product.id == k).first()
            p.amount -= int(v)
            p.sales += int(v)
            total_price += p.price * int(v)
        order.products = json.dumps(product)
        order.total_price = total_price
    try:
        db.session.add(order)
        db.session.commit()
        session["products"] = None
        session["product"] = None
        session["is_single"] = None
    except Exception as e:
        print(e)
    finally:
        return redirect(url_for("index.product"))


@user_blu.route("/clear_session")
def clear_session():
    session.clear()
    return '成功'
